<?php

namespace app\controller\admin\module\adminlog;

use app\controller\admin\module\AdminBaseController;
use think\response\Json;

/**
 * @auth-name 操作日志
 * @auth-alias adminlog
 */
class Index extends AdminBaseController
{
    protected string $modelName = 'adminActionLog';

    /**
     * @auth-name 主页
     * @auth-alias index
     * @return \think\response\View
     */
    public function index(){
        return fetch('/admin/admin_log/index');
    }

    /**
     * @auth-name 列表
     * @auth-alias list
     * @return Json
     */
    public function list(): Json
    {
        $limit = values('limit', 10);
        $this->model->customLeft = [
            'table' => 'admin',
            'on' => 'admin.id = '.$this->modelName.'.aid'
        ];
        $condition = [];
        $aid = values('aid', 0);
        $ip = values('ip');
        !empty($aid) and $condition['aid'] = $aid;
        !empty($ip) and $condition['ip'] = $ip;
        return json($this->model->getPageList($condition, $this->modelName.'.id, aid, name, method, route, param, content, ip, device, '.$this->modelName.'.addtime', $this->modelName.'.addtime desc', ['start' => ((values('page', 10) - 1) * $limit), 'limit' => $limit]));
    }

    /**
     * @auth-name 封禁IP
     * @auth-alias banip
     * @auth-request-method post
     * @return \think\response\Json
     */
    public function banIP(): \think\response\Json
    {
        if(request()->isPost()){
            $id = values('id');
            if(!empty($id)){
                $info = $this->model->getInfo(['id' => $id], 'id, ip');
                if(empty($info)){
                    return responseMsg('未找到数据');
                }
                $model = Model('access_ip');
                $ipInfo = $model->getInfo(['ip' => $info['ip']]);
                if(!empty($ipInfo)){
                    return responseMsg('此IP已经被封禁');
                }
                if($model->add(['ip' => $info['ip'], 'addtime' => time(), 'aid' => $this->admin['id']])){
                    putAdminLog('封禁IP[' . $info['ip'] . ']');
                    return responseMsg('操作成功', 200);
                }
            }
        }
        return responseMsg('操作失败');
    }
}